//
//  AppDelegate.swift
//  GerritHermes
//
//  Created by J.Zhou on 2020/2/10.
//  Copyright © 2020 周剑. All rights reserved.
//

import Cocoa
import SwiftUI
import Preferences

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var window: NSWindow!

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

    #if DEBUG
    lazy var preferencesWindowController = PreferencesWindowController(
        preferencePanes: [
            GeneralViewController(),
            ProjectsViewController(),
            AboutViewController(),
            ConsoleViewController(),
            DebugViewController()
        ]
    )
    #else
    lazy var preferencesWindowController = PreferencesWindowController(
        preferencePanes: [
            GeneralViewController(),
            ProjectsViewController(),
            ConsoleViewController(),
            AboutViewController()
        ]
    )
    #endif

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        #if DEBUG
        LocalNotification.send(title: "当前模式",
                               body: DebugModel.shared.mode.description)
        #endif

        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            RoutineChecker.shared.start()
        }

        if let button = statusItem.button {
            button.image = NSImage(named: NSImage.Name("icon@40"))
            button.imagePosition = .imageLeft
            button.action = #selector(togglePreference(_:))
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    @IBAction func cleanSavedData(_ sender: Any) {
        Log.info("清除所有存储的消息")
        do {
            try Store.cleanAll()
        } catch let error {
            Log.error("清除数据库数据失败", context: error)
        }
    }
}

private extension AppDelegate {
    @objc func togglePreference(_ sender: Any?) {
        preferencesWindowController.show(preferencePane: .general)
    }

}
